package com.rituo.lock.LuaScriptBeanCfg;

import com.rituo.lock.RedisScript;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

@Component
public class LuaLockConfiguration {

    /**
     * 向RedisScript塞入对应的Script
     * @return
     */
    @Bean
    public RedisScript redisScript() {
        RedisScript scripts = RedisScript.getInstance();
        //加锁
        DefaultRedisScript<Boolean> lockScript = new DefaultRedisScript<>();
        lockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/lock.lua")));
        lockScript.setResultType(Boolean.class);
        scripts.setLockScript(lockScript);
        //释放锁
        DefaultRedisScript<Boolean> unlockScript = new DefaultRedisScript<>();
        unlockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/unlock.lua")));
        unlockScript.setResultType(Boolean.class);
        scripts.setUnlockScript(unlockScript);
        //库存扣减
        DefaultRedisScript<Long> decrStockScript = new DefaultRedisScript<>();
        decrStockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/decr_stock.lua")));
        decrStockScript.setResultType(Long.class);
        scripts.setDecrStockScript(decrStockScript);

        return scripts;
    }

}